// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(function(){
  if (!$('body').hasClass('admin-product_as')) return;

  if ($('body').hasClass('admin-product_as-index')) {

    $('.ui.dropdown').dropdown();

    var products = gon.products;

    var productsList = new Vue({
      el: '#products-list',
      data: {
        products: products
      }
    });

    var searchInput = new Vue({
      el: '#search-input',
      data: {
        keyword: ''
      },
      methods: {
        submit: function(){
          $.get($('#search-input').data('url') + '?keyword=' + this.keyword, function(data){
            productsList.products = data;
            $('nav.pagination').remove();
          });
        }
      }
    });

    var filterSection = new Vue({
      el: '#filter-section',
      data: {
        category: '',
        financing: ''
      },
      methods: {
        submit: function(){
          location.href = '/admin/product_as?category=' + this.category + '&financing=' + this.financing
        }
      }
    });
  }

  var product_a = JSON.parse(gon.product_a);
  if (gon.screenshots){
    var screenshots = JSON.parse(gon.screenshots);
  } else {
    var screenshots = [];
  }

  var product = new Vue({
    el: '#product',
    data: {
      product:{
        name: product_a.name,
        published_at: product_a.published_at,
        category: product_a.category,
        summary: product_a.summary,
        url: product_a.url,
        logo: product_a.logo,
        description: product_a.description,
        founders: product_a.founders,
        contacts: product_a.contacts,
        financings: product_a.financings,
        cowork_records: product_a.cowork_records,
        editor_comments: product_a.editor_comments,
        screenshots: screenshots,
        delete_image: []
      }
    },
    watch:{
      "product.cowork_records": function(){
        $('.ui.dropdown').dropdown();
      },
      "product.financings": function(){
        $('.ui.dropdown').dropdown();
      }
    },
    methods: {
      sendScreen: function(){
        var formData = new FormData();
        formData.append('file', $("#file_data").get(0).files[0]);
        formData.append('imageable_type', 'ProductA');
        $.ajax({
          url: '/admin/images/create_image',
          data: formData,
          type: 'post',
          processData: false,
          contentType: false
        }).done(function(data){
          product.product.screenshots.push(data);
        })
      },
      deleteScreen: function(shot){
        var id = shot.id;
        product.product.screenshots.$remove(shot);
        product.product.delete_image.push(id);
      },
      addFounders: function(){
        metaAddLine(this, "founders", {name: '', position: '', email: '', mobile: ''});
      },
      deleteFounders: function(obj){
        this["product"]["founders"].$remove(obj);
      },
      addContacts: function(){
        metaAddLine(this, "contacts", {name: '', position: '', email: '', mobile: ''});
      },
      deleteContacts: function(obj){
        this["product"]["contacts"].$remove(obj);
      },
      addFinancings: function(){
        metaAddLine(this, "financings", {stage: '', amount:'', invertor: '', date: ''});
      },
      deleteFinancings: function(obj){
        this["product"]["financings"].$remove(obj);
      },
      addRecords: function(){
        metaAddLine(this, "cowork_records", { mode: '', staff:'', data:'', note: '' });
      },
      deleteRecords: function(obj){
        this["product"]["cowork_records"].$remove(obj);
      },
      addEditComments: function(){
        metaAddLine(this, "editor_comments", { comment: '', editor: '' });
      },
      deleteEditComments: function(obj){
        this["product"]["editor_comments"].$remove(obj);
      },
      sendData: function(){
        var data = new FormData(document.forms.namedItem('base_form'));
        var delete_image_id = (this.product.delete_image === undefined ? [] : this.product.delete_image)
        data.append('delete_image', delete_image_id);
        $.ajax({
          url: url,
          data: data,
          type: type,
          processData: false,
          contentType: false
        }).done(function(data){
          if (data.error){
            error.errors = data.error;
            $('#error_message').modal('show');
          } else {
            product.product = data['product'];
            product.product.screenshots = data['screenshots'];
            changeToEdit(data['product']['id']);
            $('.js-send-success').removeClass('move_left').delay(2000).queue(function(){
              $(this).addClass('move_left').dequeue();
            });
          }
          $('.js-loading').removeClass('loading');
        })
      }
    }
  })

  var product_id = product_a.id;
  var type = "post";
  var url = "/admin/product_as";
  $('form.loading').removeClass('loading');
  if (product_id){
    type = "patch";
    url = "/admin/product_as/"+product_id;
    $('.invisible').removeClass("invisible");
  };

  function changeToEdit(id){
    product_id = id;
    url = "/admin/product_as/"+id;
    type = "patch";
    window.history.pushState("", "", '/admin/product_as/'+id+'/edit');
  }

  $('a.js-loading').on('click', function(){
    $this = $(this);
    $this.addClass('loading');
  })

  $('#add-image-button').on('click', function(){
      $('#file_data').trigger('click');
  })

  var error = new Vue({
    el: '#error_message',
    data:{
      errors: {summary: ["",""]}
    }
  })

  function metaAddLine(object, data_name, line){
    if (object["product"][data_name]){
      object["product"][data_name].push(line);
    } else {
      object["product"][data_name] = [line];
    }
  }

  function metaSendData(object, form_name, data_name){
    var data = $(form_name).serializeArray();
    $.ajax({
      url: '/admin/product_as/' + product_id,
      data: data,
      type: 'patch'
    }).done(function(data){
      if (data.error){
      } else {
        object[data_name] = data[data_name]
      }
      $('.js-loading').removeClass('loading');
    })
  }

  $('.ui.dropdown').dropdown();
});
